# redis_client.py
import aioredis
from functools import lru_cache
from pydantic_settings import BaseSettings
from redis.asyncio import Redis
from fastapi import Request

from core.config import settings

# class Settings(BaseSettings):
#     REDIS_URL: str = "redis://localhost:6379/0"

# @lru_cache
# def get_settings():
#     return Settings()

# Redis 连接对象
redis_client: Redis | None = None


def get_redis(request: Request) -> Redis:
    return request.app.state.redis


async def init_redis_pool() -> Redis:
    # 创建 Redis 连接池
    client = Redis(
        host=settings.REDIS_HOST,  # 你可以从 env 配置中读取
        port=settings.REDIS_PORT,
        db=settings.REDIS_DB,
        password=settings.REDIS_PASSWORD,
        decode_responses=True  # 自动解码 str
    )
    # 测试连接
    await client.ping()
    return client


async def close_redis_pool(client: Redis):
    await client.close()
    await client.connection_pool.disconnect()
